#include "Socket.hpp"
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace socket_ns;
const int blags = 16;

class TcpServer;
using io_server_t = function<void(sock_addr, Analyze)>;


class Data
{
public:
    sock_addr _sockfd;
    Analyze _an;
    TcpServer *self;

    Data(sock_addr sockfd, Analyze an, TcpServer *p) : _sockfd(sockfd), _an(an), self(p)
    {
    }
};

class TcpServer
{
private:
    uint16_t _port; // 服务端端口号
    unique_ptr<Socket> ptr;

    io_server_t _func;

public:
    TcpServer(uint16_t port, io_server_t func) 
        :ptr(make_unique<TcpSocket>())
        ,_port(port)
        ,_func(func)
    {
        Analyze an("0", _port);
        ptr->BuildTcpServerSocket(an);
    }

    static void *func(void* args)
    {
        pthread_detach(pthread_self());

        Data* p = static_cast<Data*>(args);
        p->self->_func(p->_sockfd, p->_an);
        close(p->_sockfd->getfd());

        delete p;
        return nullptr;
    }

    //version 3
    void Start()
    {
        while (true)
        {
            Analyze peer;

            // 接收连接请求,带出客户端信息
            sock_addr fd = ptr->Accept(peer);
            Log(Info, "accept success");
            if (fd == nullptr)
            {
                Log(Warning, "accept fail");
                continue;
            }
       
            pthread_t thread;
            Data *data = new Data(fd, peer, this);

            // 处理该连接请求
            pthread_create(&thread,nullptr, func, data);
        }
    }

    ~TcpServer() {}
};
